package com.xh.lesson.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xh.lesson.entity.SysFun;
import com.xh.lesson.entity.SysHouse;
import com.xh.lesson.entity.SysHouseFun;
import com.xh.lesson.exception.BusinessException;
import com.xh.lesson.exception.code.BaseResponseCode;
import com.xh.lesson.service.SysFunService;
import com.xh.lesson.service.SysHouseFunService;
import com.xh.lesson.service.SysHouseService;
import com.xh.lesson.service.UpLoadService;
import com.xh.lesson.vo.req.FunAddReqVO;
import com.xh.lesson.vo.req.HomeAddReqVO;
import com.xh.lesson.vo.req.HouseAddReqVo;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UploadServiceImpl implements UpLoadService {
    @Autowired
    private SysHouseService sysHouseService;
    @Autowired
    private SysHouseFunService houseFunService;
    @Autowired
    private SysFunService funService;
    private HomeAddReqVO home;

    @Override
    public HomeAddReqVO uploadFile(MultipartFile file) throws IOException {
        System.out.println("提交");
        POIFSFileSystem fileSystem = new POIFSFileSystem(file.getInputStream());
        HSSFWorkbook sheets = new HSSFWorkbook(fileSystem);
        Row row = null;
        HSSFSheet hssfSheet = sheets.getSheetAt(0);
        if (hssfSheet==null){
            throw new BusinessException(BaseResponseCode.FILE_NOT_LEGAL);
        }
        //存houseid
        Integer temp = null;
        String houseName = null;
        if (hssfSheet != null) {
            for (int rowNum = 4; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                row = hssfSheet.getRow(rowNum);
                Integer houserid = null;
                if (row == null) {
                    continue;
                }
                if (houseName != String.valueOf(row.getCell(1))) {
                    HouseAddReqVo house = new HouseAddReqVo();
                    if (isMergedRegion(hssfSheet, rowNum, 1)) {
                        house.setHousename(getMergedRegionValue(hssfSheet, rowNum, 1));
                    } else {
                        house.setHousename(String.valueOf(row.getCell(1)));
                    }
                    if (isMergedRegion(hssfSheet, rowNum, 2)) {
                        house.setFloorspace(Float.valueOf(getMergedRegionValue(hssfSheet, rowNum, 2)));
                    } else {
                        house.setFloorspace(Float.valueOf(String.valueOf(row.getCell(2))));
                    }
                    if (isMergedRegion(hssfSheet, rowNum, 3)) {
                        house.setArea(getMergedRegionValue(hssfSheet, rowNum, 3));
                    } else {
                        house.setArea(String.valueOf(row.getCell(3)));
                    }
                    if (isMergedRegion(hssfSheet, rowNum, 4)) {
                        house.setLevel(getMergedRegionValue(hssfSheet, rowNum, 4));
                    } else {
                        house.setLevel(String.valueOf(row.getCell(4)));
                    }
                    SysHouse sysHouse = sysHouseService.soloAddHouse(house);
                    if (sysHouse == null) {
                        throw new BusinessException(BaseResponseCode.DATA_ERROR);
                    }
                    houserid = sysHouse.getHouserid();
                    temp = houserid;
                }

                FunAddReqVO fun = new FunAddReqVO();
                fun.setFun(String.valueOf(row.getCell(8)));
                fun.setFunuse(String.valueOf(row.getCell(9)));
                fun.setDepart(String.valueOf(row.getCell(10)));
                fun.setDeploy(String.valueOf(row.getCell(11)));
                fun.setEnterprise(String.valueOf(row.getCell(12)));
                fun.setForclass(String.valueOf(row.getCell(13)));
                fun.setRemark(String.valueOf(row.getCell(14)));
                SysFun sysFun = funService.soloAddFun(fun);
                if (sysFun == null) {
                    throw new BusinessException(BaseResponseCode.DATA_ERROR);
                }

                Integer funid = sysFun.getFunid();
                HomeAddReqVO home = new HomeAddReqVO();
                home.setHomenum(String.valueOf(row.getCell(5)));
                home.setRegionspace(Float.valueOf(String.valueOf(row.getCell(6))));
                home.setHomename(String.valueOf(row.getCell(7)));
                home.setFunid(funid);
                if (houserid == null) {
                    home.setHouserid(temp);
                } else {
                    home.setHouserid(houserid);
                }
                SysHouseFun sysHouseFun = houseFunService.soloAddHome(home);
                if (sysHouseFun == null) {
                    throw new BusinessException(BaseResponseCode.DATA_ERROR);
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", "true");
        return home;
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public String getMergedRegionValue(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }
        return null;
    }

    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell) {

        if (cell == null) return "";

        if (cell.getCellType() == CellType.STRING) {

            return cell.getStringCellValue();

        } else if (cell.getCellType() == CellType.BOOLEAN) {

            return String.valueOf(cell.getBooleanCellValue());

        } else if (cell.getCellType() == CellType.FORMULA) {

            return cell.getCellFormula();

        } else if (cell.getCellType() == CellType.NUMERIC) {

            return String.valueOf(cell.getNumericCellValue());

        }
        return "";
    }

    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet
     * @param row    行下标
     * @param column 列下标
     * @return
     */
    private boolean isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

}
